<template>
  <view>
    <!-- 触发按钮 -->
    <view @click="openSelector">
      <slot :open="openSelector">
        <button class="media-selector-trigger">
          选择媒体
        </button>
      </slot>
    </view>

    <!-- 使用 u-action-sheet 选择器 -->
    <u-action-sheet 
      :actions="actionList" 
      :show="show" 
      :closeOnClickOverlay="true" 
      :safeAreaInsetBottom="true"
      @close="closeSelector" 
      @select="onActionSelect"
    ></u-action-sheet>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import permission from '@/utils/permission'

interface Props {
  // 是否显示相机选项
  showCamera?: boolean
  // 是否显示相册选项
  showAlbum?: boolean
  // 最大选择数量
  maxCount?: number
  // 图片大小限制
  sizeType?: string[]
  // 是否压缩
  compressed?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showCamera: true,
  showAlbum: true,
  maxCount: 1,
  sizeType: () => ['compressed'],
  compressed: true
})

const emit = defineEmits<{
  success: [files: any[]]
  fail: [error: any]
  cancel: []
}>()

const show = ref(false)

// 检查权限可用性
const cameraAvailable = computed(() => props.showCamera)
const albumAvailable = computed(() => props.showAlbum)

// 生成操作列表
const actionList = computed(() => {
  const actions = []
  
  if (props.showCamera) {
    actions.push({
      name: '拍照',
      value: 'camera',
      color: '#333'
    })
  }
  
  if (props.showAlbum) {
    actions.push({
      name: '从相册选择',
      value: 'album',
      color: '#333'
    })
  }
  
  return actions
})

// 打开选择器
const openSelector = () => {
  console.log('打开选择器')
  show.value = true
}

// 关闭选择器
const closeSelector = () => {
  show.value = false
  emit('cancel')
}

// 处理操作选择
const onActionSelect = (item: any) => {
  console.log('选择操作:', item)
  
  if (item.value === 'camera') {
    selectCamera()
  } else if (item.value === 'album') {
    selectAlbum()
  }
}

// 选择相机
const selectCamera = async () => {
  if (!cameraAvailable.value) return
  
  try {
    // 使用permission.ts检查相机权限，会自动显示权限说明
    const result = await permission.permissionCheck('CAMERA')
    if (result !== 1) {
      closeSelector()
      return
    }
    
    // 调用相机功能
    uni.chooseImage({
      count: props.maxCount,
      sizeType: props.sizeType,
      sourceType: ['camera'],
      success: (res) => {
        const files = res.tempFiles || res.tempFilePaths
        emit('success', Array.isArray(files) ? files : [files])
        closeSelector()
      },
      fail: (err) => {
        emit('fail', err)
        closeSelector()
      }
    })
  } catch (error) {
    emit('fail', error)
    closeSelector()
  }
}

// 选择相册
const selectAlbum = async () => {
  if (!albumAvailable.value) return
  
  try {
    // 根据Android版本选择合适的权限
    let permissionType = 'EXTERNAL_STORAGE'
    
    // #ifdef APP-PLUS
    if (plus.os.name === 'Android') {
      const version = plus.os.version || '0'
      const majorVersion = parseInt(version.split('.')[0]) || 0
      
      if (majorVersion >= 14) {
        permissionType = 'MEDIA_VISUAL_SELECTED'
      } else if (majorVersion >= 13) {
        permissionType = 'MEDIA_IMAGES'
      }
    }
    // #endif
    
    // 使用permission.ts检查相册权限
    const result = await permission.permissionCheck(permissionType)
    if (result !== 1) {
      closeSelector()
      return
    }
    
    // 调用相册功能
    uni.chooseImage({
      count: props.maxCount,
      sizeType: props.sizeType,
      sourceType: ['album'],
      success: (res) => {
        const files = res.tempFiles || res.tempFilePaths
        emit('success', Array.isArray(files) ? files : [files])
        closeSelector()
      },
      fail: (err) => {
        emit('fail', err)
        closeSelector()
      }
    })
  } catch (error) {
    console.error('选择相册异常:', error)
    emit('fail', error)
    closeSelector()
  }
}

</script>

<style lang="scss" scoped>
.media-selector-trigger {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  font-size: inherit;
  color: inherit;
}

/* 确保整个容器都可以点击 */
view {
  cursor: pointer;
}
</style>
